import Vue from 'vue';
import Vuex from 'vuex';
import { nanoid } from 'nanoid';
import dataFormat from '@/utils/dateFormat';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    tagsList: [],
    record: {
      type: '-',
      note: '',
      amount: 0,
      selectedTagsList: []
    },
    recordList: [],
    showDate: 'day',
    recordResultList: []
  },
  mutations: {
    fetchTagsList(state) {
      state.tagsList = JSON.parse(localStorage.getItem('tagsList') || '[]');
      console.log('Fetched tagsList:', state.tagsList);
    },
    saveTagsList(state) {
      localStorage.setItem('tagsList', JSON.stringify(state.tagsList));
      console.log('Saved tagsList:', state.tagsList);
    },
    addTag(state) {
      const tag = prompt('请输入标签名：');
      if (!tag) return;
      const t = state.tagsList.map(item => item.tagName);
      if (!t.includes(tag)) {
        state.tagsList = [...state.tagsList, { id: nanoid(8), tagName: tag }];
        console.log('Added tag:', tag);
      } else {
        alert('标签不能重复');
      }
    },
    delTag(state, id) {
      state.tagsList = state.tagsList.filter(tag => tag.id !== id);
      console.log('Deleted tag with ID:', id);
    },
    changeTagName(state, newTag) {
      for (let i = 0; i < state.tagsList.length; i++) {
        if (state.tagsList[i].tagName === newTag.tagName) {
          alert('标签名已存在');
          return;
        }
      }
      for (let i = 0; i < state.tagsList.length; i++) {
        if (state.tagsList[i].id === newTag.id) {
          state.tagsList[i].tagName = newTag.tagName;
          console.log('Changed tag name:', newTag.tagName);
          return;
        }
      }
    },
    fetchRecordList(state) {
      state.recordList = JSON.parse(localStorage.getItem('recordList') || '[]');
      console.log('Fetched recordList:', state.recordList);
    },
    updateRecord(state, dateObj) {
      state.record.id = nanoid();
      state.record.date = dataFormat('YYYY-mm-dd HH:MM', new Date());
      state.record[dateObj.name] = dateObj.value;
      console.log('Updated record:', state.record);
    },
    addRecord(state, date) {
      state.recordList.push(date);
      console.log('Added record:', date);
    },
    saveRecordList(state) {
      localStorage.setItem('recordList', JSON.stringify(state.recordList));
      console.log('Saved recordList:', state.recordList);
    },
    cleanRecord(state) {
      state.record.selectedTagsList = [];
      state.record.note = '';
      console.log('Cleaned record:', state.record);
    }
  },
});

export default store;

